<template>
  <div>
    <!-- 内容 -->
    <slot />
    <div class="h-6 py-4" ref="loadingTarget">
      <!-- 加载更多 -->
      <z-svg-icon
        v-show="loading"
        class="w-4 h-4 mx-auto animate-spin"
        name="infinite-load"
      ></z-svg-icon>
      <!-- 没有更多数据 -->
      <p v-if="isFinished" class="text-center text-base text-zinc-400">
        {{ text }}
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useVModel, useIntersectionObserver } from '@vueuse/core'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  isFinished: {
    type: Boolean,
    default: false
  },
  text: {
    type: String,
    default: '已经没有更多数据了！'
  }
})

const emits = defineEmits(['onLoad', 'update:modelValue'])

// 处理loading状态
const loading = useVModel(props)
// 滚动元素
const loadingTarget = ref(null)
// 是否可见
const targetIsIntersecting = ref(false)

// 监听元素是否进入可视区域
const { stop } = useIntersectionObserver(
  loadingTarget,
  ([{ isIntersecting }]) => {
    targetIsIntersecting.value = isIntersecting
    emitLoad()
  }
)

/**
 * 触发 load 事件
 */
const emitLoad = () => {
  setTimeout(() => {
    // 当加载更多视图可见且 loading 为 false 同时，数据尚未加载完，处理加载更多数据
    if (targetIsIntersecting.value && !loading.value && !props.isFinished) {
      loading.value = true
      // 触发加载事件
      emits('onLoad')
    }
  }, 100)
}

/**
 * 监听 loading 变化
 */
watch(loading, emitLoad)
</script>

<style lang="scss" scoped></style>
